import React, { useState, useEffect } from 'react';
import { Card, Button, Descriptions, Spin, message, Result, Typography, Divider, Tag, Space } from 'antd';
import { useParams, useNavigate } from 'react-router-dom';
import { materialOrderService } from '../../services/materialOrderService';
import { DownloadOutlined, FilePdfOutlined, FileExcelOutlined, FileZipOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

// 根据文件类型返回对应的图标
const getFileIcon = (fileType) => {
  if (!fileType) return <FilePdfOutlined />;
  
  const type = fileType.toLowerCase();
  if (type.includes('pdf')) return <FilePdfOutlined />;
  if (type.includes('excel') || type.includes('xlsx') || type.includes('xls')) return <FileExcelOutlined />;
  if (type.includes('zip') || type.includes('rar')) return <FileZipOutlined />;
  return <FilePdfOutlined />;
};

// 订单状态标签
const OrderStatusTag = ({ status }) => {
  let color = 'default';
  let text = '未知状态';
  
  switch (status) {
    case 'pending':
      color = 'warning';
      text = '待支付';
      break;
    case 'paid':
      color = 'success';
      text = '已支付';
      break;
    case 'completed':
      color = 'green';
      text = '已完成';
      break;
    case 'cancelled':
      color = 'error';
      text = '已取消';
      break;
    case 'refunded':
      color = 'volcano';
      text = '已退款';
      break;
    default:
      break;
  }
  
  return <Tag color={color}>{text}</Tag>;
};

const MaterialOrderDetail = () => {
  const { orderNumber } = useParams();
  const navigate = useNavigate();
  
  const [loading, setLoading] = useState(true);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [order, setOrder] = useState(null);

  // 获取订单详情
  useEffect(() => {
    const fetchOrderDetails = async () => {
      try {
        setLoading(true);
        const data = await materialOrderService.getOrderDetails(orderNumber);
        setOrder(data);
      } catch (error) {
        console.error('获取订单详情失败:', error);
        message.error('获取订单详情失败: ' + (error.message || '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchOrderDetails();
  }, [orderNumber]);

  // 处理下载材料
  const handleDownload = async () => {
    try {
      setDownloadLoading(true);
      
      // 生成下载令牌
      const tokenResult = await materialOrderService.generateDownloadToken(orderNumber);
      
      if (tokenResult && tokenResult.downloadUrl) {
        // 打开下载链接
        window.open(tokenResult.downloadUrl, '_blank');
        message.success('开始下载材料');
      } else {
        message.error('获取下载链接失败');
      }
    } catch (error) {
      console.error('下载材料失败:', error);
      message.error('下载材料失败: ' + (error.message || '未知错误'));
    } finally {
      setDownloadLoading(false);
    }
  };

  // 返回材料列表
  const backToMaterials = () => {
    navigate('/materials');
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <p>加载订单信息...</p>
      </div>
    );
  }

  if (!order) {
    return (
      <Result
        status="error"
        title="订单不存在"
        subTitle="无法找到该订单信息，请检查订单号是否正确"
        extra={
          <Button type="primary" onClick={backToMaterials}>
            返回材料列表
          </Button>
        }
      />
    );
  }

  return (
    <Card className="order-detail-container">
      <div className="order-header">
        <Title level={3}>订单详情</Title>
        <OrderStatusTag status={order.status} />
      </div>
      
      <Divider />
      
      <Descriptions title="订单信息" bordered column={{ xs: 1, sm: 2, md: 3 }}>
        <Descriptions.Item label="订单号">{order.orderNumber}</Descriptions.Item>
        <Descriptions.Item label="创建时间">{new Date(order.createdAt).toLocaleString()}</Descriptions.Item>
        <Descriptions.Item label="状态"><OrderStatusTag status={order.status} /></Descriptions.Item>
        <Descriptions.Item label="总金额">¥{order.totalAmount}</Descriptions.Item>
        {order.paymentTime && (
          <Descriptions.Item label="支付时间">
            {new Date(order.paymentTime).toLocaleString()}
          </Descriptions.Item>
        )}
      </Descriptions>
      
      <Divider />
      
      <Descriptions title="材料信息" bordered>
        <Descriptions.Item label="材料名称" span={3}>{order.material?.title}</Descriptions.Item>
        <Descriptions.Item label="材料描述" span={3}>{order.material?.description}</Descriptions.Item>
        <Descriptions.Item label="价格">¥{order.material?.price}</Descriptions.Item>
        <Descriptions.Item label="文件类型">
          <Space>
            {getFileIcon(order.material?.fileType)}
            <Text>{order.material?.fileType || '未知'}</Text>
          </Space>
        </Descriptions.Item>
      </Descriptions>
      
      <Divider />
      
      <Descriptions title="客户信息" bordered>
        <Descriptions.Item label="姓名">{order.customerInfo?.name}</Descriptions.Item>
        <Descriptions.Item label="电子邮箱">{order.customerInfo?.email}</Descriptions.Item>
        <Descriptions.Item label="电话">{order.customerInfo?.phone}</Descriptions.Item>
        {order.customerInfo?.address && (
          <Descriptions.Item label="地址" span={3}>{order.customerInfo.address}</Descriptions.Item>
        )}
        {order.customerInfo?.company && (
          <Descriptions.Item label="公司">{order.customerInfo.company}</Descriptions.Item>
        )}
        {order.customerInfo?.taxId && (
          <Descriptions.Item label="税号">{order.customerInfo.taxId}</Descriptions.Item>
        )}
        {order.customerInfo?.notes && (
          <Descriptions.Item label="备注" span={3}>{order.customerInfo.notes}</Descriptions.Item>
        )}
      </Descriptions>
      
      <div className="action-buttons" style={{ marginTop: '20px', textAlign: 'center' }}>
        {order.status === 'paid' || order.status === 'completed' ? (
          <Button 
            type="primary" 
            icon={<DownloadOutlined />} 
            size="large"
            onClick={handleDownload}
            loading={downloadLoading}
          >
            下载材料
          </Button>
        ) : (
          order.status === 'pending' && (
            <Button 
              type="primary"
              onClick={() => navigate(`/material/payment/${orderNumber}`)}
            >
              去支付
            </Button>
          )
        )}
        
        <Button 
          style={{ marginLeft: '10px' }}
          onClick={backToMaterials}
        >
          返回材料列表
        </Button>
      </div>
    </Card>
  );
};

export default MaterialOrderDetail;